package day04.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/18 14:13
 */

public class FirstServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        System.out.println(new Date() + ": 服务端读到数据 -> " + byteBuf.toString(StandardCharsets.UTF_8));

        System.out.println(new Date() + "接受数据完毕，发送反馈中");

        ByteBuf out = getByteBuf(ctx);
        ctx.channel().writeAndFlush(out);

    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        // 1. 获取二进制抽象ByteBuf
        ByteBuf buffer = ctx.alloc().buffer();

        // 2. 准备数据，指定字符串的字符集为UTF-8
        byte[] bytes = "你好，client".getBytes(StandardCharsets.UTF_8);

        // 3. 填充数据到ByteBuf
        buffer.writeBytes(bytes);

        return buffer;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有客户端连接中，确认客户端信息");
        ByteBuf buffer = ctx.alloc().buffer();
        byte[] bytes = "您正在连接中".getBytes(StandardCharsets.UTF_8);
        buffer.writeBytes(bytes);
        ctx.channel().writeAndFlush(buffer);
    }
}
